<template>
    <div class="table-container">
        <Layout>
            <Header class="tb-head">
                <div class="search-box">
                    <Row>
                        <Col span="20">
                        <slot name="searchBox" style="float: left"></slot>
                        <div class="float: left">
                            <Button type="primary" style="margin-left: 10px" v-if="!hasMoreSer" @click="getData" v-waves>搜索</Button>
                            <!-- 导出Excel -->
                            <Button type="primary" icon="ios-cloud-download-outline" :loading="downloadLoading" style="margin-left: 10px" v-if="needExport" @click="handleExport" v-waves>导出Excel</Button>
                            <!-- 导出压缩包 -->
                            <Button type="primary" icon="ios-cloud-download-outline" :loading="zipLoading" style="margin-left: 10px" v-if="needExportZip" @click="handleExportZip" v-waves>导出Zip</Button>
                            <Button type="primary" style="margin-left: 10px" v-if="tableOption.needMoreSer" :icon="searchIcon" @click="showMore" v-waves>高级搜索</Button>
                        </div>
                        </Col>
                        <Col span="4" style="text-align: right">
                        <Button type="primary" style="margin-right: 10px" @click="handleAdd" v-waves>添加</Button>
                        <Poptip trigger="hover" placement="bottom-end" title="提示" content="刷新会将搜索内容清空">
                            <Button type="success" @click="handleRefresh" v-waves>刷新</Button>
                        </Poptip>
                        </Col>
                    </Row>
                </div>
            </Header>
            <Content class="tb-con">
                <div class="tb-con-ser-con" v-if="hasMoreSer">
                    <slot name="searchMoreBox" style="float: left"></slot>
                    <Button type="primary" style="margin-left: 10px" @click="getData" v-waves>搜索</Button>
                </div>
                <Table class="tb-con-table" @on-selection-change="changeSelect" :loading="tbLoading" :data="tableData" border :columns="columns" stripe />
            </Content>
            <Footer class="tb-foot">
                <Row>
                    <Col span="6"> &nbsp;
                    <Button type="error" @click="handleRemove({}, 'more')" v-waves>批量删除</Button>
                    </Col>
                    <Col span="18" style="text-align:right">
                    <paginarion style="margin-right: 10px" :pageInfo.sync="pageInfo" @pageChange="getData"></paginarion>
                    </Col>
                </Row>
            </Footer>
            <!-- 弹出的对话框 -->
            <Modal v-model="showModal" :title="dialogTitle" width="60%">
                <Form :model="formCustom" ref="formCustom" label-position="right" :label-width="100">
                    <FormItem v-for="(item,index) in formCustom.items" :rules="ruleCustom[index]" :key="index" :label="item.label" :prop="'items.' + index + '.value'" >
                        <Input :type="item.type" v-model="item.value"></Input>
                    </FormItem>
                </Form>
                <div slot="footer">
                    <Button type="default" @click="showModal = false">取消</Button>
                    <Button type="primary" :loading="buttonLoading" @click="commitModal">确认</Button>
                </div>
            </Modal>
        </Layout>
    </div>
</template>

<script>
    import {
        tbAction
    } from '@/api/table.js';
    import waves from '@/directive/waves' // 水波纹指令
    import paginarion from './page.vue';
    import arrUtil from '@/libs/unique.js';
    import validate from '@/libs/validate.js'
    import {
        parseTime
    } from '@/libs/common.js'
    export default {
        props: {
            tableOption: {
                type: Object
            },
            searchInfo:{
                type: Object
            }
        },
        components: {
            paginarion
        },
        directives: {
            waves
        },
        data() {
            return {
                // 表单的数据
                formCustom: {
                    items:this.tableOption.formItems
                },
                // 表单验证的规则
                ruleCustom: [],
                // 导出excel
                needExport: this.tableOption.showExport || true,
                downloadLoading: false,
                // 导出zip
                zipLoading:false,
                needExportZip: this.tableOption.showExportZip || true,
                // 表格数据
                tableData: [],
                // 高级搜索按钮的图标
                searchIcon: "ios-arrow-down",
                // 表格列的数据
                columns: this.tableOption.cols,
                // 控制是否显示高级搜索块
                hasMoreSer: false,
                // 分页的数据
                pageInfo: {
                    cur: 1,
                    total: 0,
                    size: 20
                },
                // 表格的loading
                tbLoading: true,
                // 控制对话框显示隐藏
                showModal: false,
                // 对话框的标题
                dialogTitle: "",
                // 判断点击的是编辑还是添加按钮
                handleType: '',
                // 删除原因
                delRemark: "",
                // 按钮的loading
                buttonLoading: false,
                // 选中的数据的集合
                checkIds: [],
                // 编辑的id
                updateId:"",
                // 导出文件的文件名
                fileName:""

            }
        },
        methods: {
            // 勾选按钮的事件
            changeSelect(selecitons) {
                // this.checkIds = selecitons;
                selecitons.map(item => {
                    this.checkIds.push(item.id)
                })

            },
            // 获取表格数据
            getData() {
                let params = {};
                let url = '';
                // 根据searchInfo判断是否为搜索
                if (JSON.stringify(this.searchInfo) != '{}') {
                    url = this.tableOption.apis['search'];
                    params = this.searchInfo;
                } else {
                    url = this.tableOption.apis['list']
                    params = {
                        pageNum: this.pageInfo.cur,
                        pageSize: this.pageInfo.size
                    }
                }
                this.tbLoading = true;
                tbAction(params, url).then(res => {
                    this.tableData = res.data.list;
                    this.tbLoading = false;
                    this.pageInfo.total = res.data.total;
                }).catch(err => {
                    this.tbLoading = false;
                })

            },
            // 编辑事件,先进行判断是否需要打开新的页面
            handleEdit(param) {
                let payload = param;
                if (!payload.needNew) {
                    this.dialogTitle = '编辑';
                    this.handleType = "update";
                    this.updateId = param.data.id;
                    this.showModal = true;
                    this.formCustom.items.map(item => {
                        item.value = param.data[item.key]
                    })
                } else {
                    this.$router.push({
                        path: param.path,
                        query: param.query
                    })
                }
            },
            // 删除事件
            handleRemove(id, type) {
                let resultArr = []
                // 判断是单个删除还是批量删除
                if (type == 'one') {
                    resultArr = id;
                } else {
                    // 将选中的数组去重避免重复
                    resultArr = arrUtil.unique(this.checkIds).join(',');
                }
                // iview confirm this指向问题
                const _self = this;
                this.$Modal.confirm({
                    title: '提示',
                    content: '该操作将永久删除数据，你确定要继续吗？',
                    onOk: () => {
                        tbAction({
                            id: resultArr
                        }, this.tableOption.apis.remove).then(res => {
                            this.tbLoading = true;
                            this.getData();
                            if (res.status == 'SUCCESS') {
                                this.$Message.success('操作成功！');
                            }
                        }).catch(err => {
                            this.tbLoading = false;
                        })
                    },
                    onCancel: () => {

                    }
                })
            },
            // 添加事件
            handleAdd() {
                this.$emit('handleAdd');
                this.formCustom.items.map(item => {
                    item.value = ''
                })
            },
            // 验证点击添加按钮后的操作，是否需要新打开一个页面，以及修改对话框的标题
            afterAdd(param) {
                if (!param.needNew) {
                    this.dialogTitle = '添加';
                    this.showModal = true;
                    this.handleType = 'save';
                } else {
                    this.$router.push({
                        path: param.path,
                        query: param.query
                    })
                }
            },
            // 刷新表格数据
            handleRefresh() {
                // 将搜索的字段清空
                for (var x in this.searchInfo) {
                    this.searchInfo[x] = undefined;
                }
                this.tbLoading = true;
                this.getData();
            },
            // 高级搜索事件
            showMore() {
                if (!this.hasMoreSer) {
                    this.searchIcon = 'ios-arrow-up'
                } else {
                    this.searchIcon = 'ios-arrow-down'
                }
                this.hasMoreSer = !this.hasMoreSer;
            },
            // 对话框的提交事件，根据父组件传过来的参数判断表单验证是否通过
            commitModal() {
                let paramOk = true;
                this.$refs.formCustom.validate((valid) => {
                    if (valid) {
                       paramOk = true; // 允许提交
                    } else {
                       paramOk = false; // 允许提交
                    }
                });
                if (paramOk) {
                    let api = '';
                    let params = {
                        id: this.updateId
                    };
                    this.formCustom.items.map(item => {
                        params[item.key] = item.value
                    })
                    this.buttonLoading = true;
                    tbAction(params, this.tableOption.apis[this.handleType]).then(res => {
                        this.buttonLoading = false;
                        if (res.code == '200') {
                            this.showModal = false;
                            this.tbLoading = true;
                            this.$Message.success('操作成功！');
                            this.getData();
                        } else {
                            this.showModal = false;
                            this.tbLoading = false;
                            this.$Message.error(res.message)
                        }
                    }).catch(err => {
                        this.tbLoading = false;
                        this.buttonLoading = false;
                    })
                }
            },
            //导出Excel文件的事件
            handleExport() {
                this.$Modal.confirm({
                    title:"提示",
                    render: (h) => {
                        return [h('div',{
                            style: {
                                margin: '5px',
                                color: '#aaa'
                            },
                        },'请输入导出的文件名，不填写内容则默认为 ‘table-list’ '),h('Input', {
                            props: {
                                value: this.fileName,
                                autofocus: true,
                            },
                            on: {
                                input: (val) => {
                                    this.fileName = val;
                                }
                            }
                        })]
                    },
                    onOk:() => {
                        this.exportExcel(this.fileName);
                    },
                    onCancel: () => {
                        this.$Message.info('取消导出');
                    }
                })
            },            
            exportExcel(value) {
                let tHeader = [];
                let filterVal = [];
                this.columns.map((res, index) => {
                    if (index !== 0 && res.title != '操作') {
                        tHeader.push(res.title)
                        filterVal.push(res.key)
                    }
                });
                this.downloadLoading = true
                import ('@/vendor/Export2Excel').then(excel => {
                    const data = this.formatJson(filterVal, this.tableData.slice(0, this.pageInfo.size))
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: value || 'table-list'
                    })
                    this.downloadLoading = false
                })
            },
            
            // 导出为zip
            handleExportZip() {
                this.$Modal.confirm({
                    title:"提示",
                    render: (h) => {
                        return [h('div',{
                            style: {
                                margin: '5px',
                                color: '#aaa'
                            },
                        },'请输入导出的文件名，不填写内容则默认为 ‘table-list’ '),h('Input', {
                            props: {
                                value: this.fileName,
                                autofocus: true,
                            },
                            on: {
                                input: (val) => {
                                    this.fileName = val;
                                }
                            }
                        })]
                    },
                    onOk:() => {
                        this.exportZip(this.fileName);
                    },
                    onCancel: () => {
                        this.$Message.info('取消导出');
                    }
                })
            },
            exportZip(value) {
                let tHeader = [];
                let filterVal = [];
                this.columns.map((res, index) => {
                    if (index !== 0 && res.title != '操作') {
                        tHeader.push(res.title)
                        filterVal.push(res.key)
                    }
                });
                this.zipLoading = true
                import ('@/vendor/Export2Zip').then(zip => {
                    const data = this.formatZipJson(filterVal, this.tableData.slice(0, this.pageInfo.size))
                    zip.export_txt_to_zip(tHeader, data, value || 'table-list', value || 'table-list')
                    this.zipLoading = false
                })
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    if (j === 'timestamp') {
                        return parseTime(v[j])
                    } else {
                        return v[j]
                    }
                }))
            },
            formatZipJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]))
            },
        },
        mounted() {
            this.getData();
        },
        created() {
            // 设置表单验证的规则
            this.tableOption.formItems.map(res => {
                let obj = {};
                if (res.rule == 'required') {
                    obj = {
                        required: true,
                        trigger: 'blur',
                        message: '不能为空！'
                    }
                } else if(res.rule){
                    obj = {
                        required: true,
                        pattern: validate[res.rule],
                        trigger: 'blur',
                        message: '格式错误！'
                    }
                }
                this.ruleCustom.push(obj);
            })
        }
    }
</script>

<style lang="less" scoped>
    .table-container {
        width: 98%;
        height: 98%;
        margin: 1%;
        background-color: #fff;
        box-shadow: 0 1px 2px #ccc;
        .tb-head {
            background-color: #fff;
            .search-box {
                padding: 0 20px;
            }
        }
        .tb-con {
            background-color: #fff;
            &-ser-con {
                padding: 0 70px;
                min-height: 54px;
                line-height: 50px;
                overflow-y: auto;
                margin-bottom: 10px;
            }
            &-table {}
        }
        .tb-foot {
            padding: 10px;
            background-color: #fff;
        }
    }
</style>

